﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Tesla.Util.UIUtilities
{
    public class TemplateFieldColumn<TControl> : ITemplate
        where TControl : WebControl, new()
    {
        private string _colName;
        private string _cntlId;
        private object _dataSource;
        private static int _id = 1;
        public TemplateFieldColumn(string columnName)
            : this(columnName, string.Empty, null) { }

        public TemplateFieldColumn(string columnName, string controlId)
            : this(columnName, controlId, null) { }

        public TemplateFieldColumn(string columnName, string controlId, object sourceData)
        {
            _colName = columnName;
            _cntlId = controlId;
            _dataSource = sourceData;
        }

        #region ITemplate Members

        public void InstantiateIn(Control container)
        {
            TControl control = new TControl();
            control.ID = _cntlId + "~" + _id.ToString();
            control.DataBinding += new EventHandler(control_DataBinding);
            container.Controls.Add(control);
            _id++;
        }

        void control_DataBinding(object sender, EventArgs e)
        {
            TControl control = sender as TControl;

            GridViewRow container = (GridViewRow)control.NamingContainer;
            object dataValue = DataBinder.Eval(container.DataItem, _colName);

            switch (control.GetType().Name)
            {
                case "TextBox":
                    TextBox txt = control as TextBox;
                    txt.Text = dataValue != DBNull.Value ? dataValue.ToString() : string.Empty;
                    break;
                default:
                    break;
            }
        }

        //void hour_DataBinding(object sender, EventArgs e)
        //{
        //    TextBox tbx = (TextBox)sender;
        //    tbx.Width = 30;
        //    GridViewRow container = (GridViewRow)tbx.NamingContainer;

        //    object dataValue = DataBinder.Eval(container.DataItem, _colName);

        //    if (dataValue != DBNull.Value)
        //    {
        //        tbx.Text = dataValue.ToString();
        //    }
        //}

        #endregion
    }
}
